#if !defined(LOG_TAG)
    #define LOG_TAG                    "mod"
#endif
#undef LOG_LVL
#if defined(MOD_LOG_LVL)
    #define LOG_LVL                    MOD_LOG_LVL
#endif

#include "ccu_modules.h"
#include "ccu.h"
#include "ccu_common.h"
#include "uconfig.h"

static int32_t ccu_create_uconfig(struct ccu* pccu)
{
	int32_t ret;

	ret = create_init_uconfig(&pccu->puconfig);
	if(ret < 0){
		log_e("create uconfig error");
		return ret;
	}

	return 0;
}

static int32_t ccu_destroy_uconfig(struct ccu* pccu)
{
	if(pccu->puconfig){
		release_destroy_uconfig(pccu->puconfig);
		pccu->puconfig = NULL;
	}

	return 0;
}

static int32_t ccu_create_threadpool(struct ccu* pccu)
{
	int32_t ret;

	ret = create_init_threadpool(&pccu->pthreadpool);
	if(ret < 0){
		log_e("create threadpool error");
		return ret;
	}

	return 0;
}

static int32_t ccu_destroy_threadpool(struct ccu* pccu)
{
	if(pccu->pthreadpool){
		release_destroy_threadpool(pccu->pthreadpool);
		pccu->pthreadpool = NULL;
	}

	return 0;
}

void sample_task(void* arg) {
    int* num = (int*)arg;
	usleep(100000);
    printf("Processing task %d\n", *num);
    free(num);
}

int32_t ccu_start_module(void *context)
{
    int32_t ret = 0;
	int i = 0;
	struct ccu *pccu = (struct ccu *)context;
	struct uconfig_info *pinfo = &pccu->puconfig->info;

	struct threadpool *pthreadpool;
	pthreadpool = pccu->pthreadpool;
	ret = pthreadpool->op->start(pthreadpool, &pinfo->threadpool_cfg);
	if(ret < 0){
		log_e("start threadpool failed");
		return ret;
	}

	for (int i = 0; i < 10; i++) {
        int* arg = malloc(sizeof(int));
        *arg = i;
        pthreadpool->op->add_task(pthreadpool, sample_task, arg);
    }

	return ret;
}

int32_t ccu_stop_module(void *context)
{
    int32_t ret = 0;
	struct ccu *pccu = (struct ccu *)context;

	struct threadpool *pthreadpool;
	pthreadpool = pccu->pthreadpool;
	if(pthreadpool->enable){
		pthreadpool->op->stop(pthreadpool);
	}

	return ret;
}

int32_t ccu_create_module(void *context)
{
    int32_t ret = 0;
	struct ccu *pccu = (struct ccu *)context;

	pccu->op->create_uconfig       = ccu_create_uconfig;
	pccu->op->destroy_uconfig      = ccu_destroy_uconfig;
	pccu->op->create_threadpool    = ccu_create_threadpool;
	pccu->op->destroy_threadpool   = ccu_destroy_threadpool;

	ret = pccu->op->create_uconfig(pccu);
	if(ret < 0){
		log_e("create uconfig error");
		return ret;
	}

	ret = pccu->op->create_threadpool(pccu);
	if(ret < 0){
		log_e("create threadpool error");
		return ret;
	}

    return ret;
}

int32_t ccu_destroy_module(void *context)
{
	int32_t ret = 0;
	struct ccu *pccu = (struct ccu *)context;

	pccu->op->destroy_threadpool(pccu);
	pccu->op->destroy_uconfig(pccu);

    return ret;
}
